/*
 * @Author: yanjikun
 * @Date: 2021-06-17 10:21:39
 * @LastEditors: yanjikun
 * @LastEditTime: 2021-06-18 16:26:53
 * @Description: file content
 */
import axios, { AxiosRequestConfig, Canceler } from 'axios'
const pendingMap = new Map<string, Canceler>()
function getPendingKey(config: AxiosRequestConfig) {
  return [config.method, config.url].join('&')
}
export function addPending(config: AxiosRequestConfig): void {
  removePending(config)
  const pendingKey = getPendingKey(config)
  config.cancelToken =
    config.cancelToken ||
    new axios.CancelToken((cancel: Canceler) => {
      if (!pendingMap.has(pendingKey)) {
        pendingMap.set(pendingKey, cancel)
      }
    })
}

export function removePending(config: AxiosRequestConfig): void {
  const pendingKey = getPendingKey(config)
  if (pendingMap.has(pendingKey)) {
    const cancel = pendingMap.get(pendingKey)
    cancel && cancel(pendingKey)
    pendingMap.delete(pendingKey)
  }
}

export function removeAllPending(): void {
  pendingMap.forEach((value: Canceler, key: string) => {
    value && value(key)
  })
  pendingMap.clear()
}
